package com.demo.gateway.filter;

import java.nio.charset.Charset;
import java.text.ParseException;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import com.alibaba.fastjson.JSON;
import com.demo.commons.results.CommonEnum;
import com.demo.commons.results.CommonResult;
import com.demo.commons.results.Results;
import com.demo.gateway.redis.RedisClient;
import com.nimbusds.jose.JWSObject;

import cn.hutool.core.util.StrUtil;
import reactor.core.publisher.Mono;

/**
 * 将登录用户的JWT转化成用户信息的全局过滤器 
 * @author yangjian
 * @version 创建时间：2022年2月22日 上午11:00:53
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

	private static Logger LOGGER = LoggerFactory.getLogger(AuthGlobalFilter.class);

	@Autowired
	private RedisClient redisClient;

	private static final String prifix = "access:";
	
	@Override
	public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
		String token = getToken(exchange);
		if (StrUtil.isEmpty(token)) {
			return chain.filter(exchange);
		}
		if (!redisClient.isExist(prifix + token)) {  
			ServerHttpResponse response = exchange.getResponse();
			CommonResult<?> result = Results.build(CommonEnum.ACCESS_TOKEN_ERROR);
			DataBuffer buffer = response.bufferFactory()
					.wrap(JSON.toJSONString(result).getBytes(Charset.forName("UTF-8")));
			return response.writeWith(Mono.just(buffer));
		}
		try {
			JWSObject jwsObject = JWSObject.parse(token);
			String userStr = jwsObject.getPayload().toString();
			LOGGER.info("AuthGlobalFilter.filter() user:{}", userStr);
			ServerHttpRequest request = exchange.getRequest().mutate().header("user", userStr).build();
			exchange = exchange.mutate().request(request).build();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return chain.filter(exchange);
	}

	@Override
	public int getOrder() {
		return 0;
	}

	private String getToken(ServerWebExchange exchange) {
		String token = exchange.getRequest().getHeaders().getFirst("Authorization");
		if (StringUtils.isEmpty(token)) {
			token = exchange.getRequest().getQueryParams().getFirst("access_token");
		}
		if(StringUtils.isNotBlank(token)) {
			token = token.replace("Bearer ", "");
		}
		return token;
	}
}
